package ex304.bank;

import java.util.Arrays;

public class AccountManager {
    private Account[] accountList; // 存放账户的数组
    private int size;              // 当前账户数

    public AccountManager() {
        accountList = new Account[50];
        size = 0;
    }

    /**
     * 查询指定 id 的账户
     *
     * @param id
     * @return 查找成功返回账户对象，查找失败返回 null
     */
    public Account getAccount(String id) {
        Account account = null;
        for (int i = 0; i < size; i++) {
            if (id.equals(accountList[i].getId())) {
                account = accountList[i];
                break;
            }
        }
        return account;
    }

    /**
     * 查询指定 id 的账户的下标
     *
     * @param id
     * @return 查找成功返回账户的下标，查找失败返回 -1
     */
    public int indexOf(String id) {
        int index = -1;
        for (int i = 0; i < size; i++) {
            if (id.equals(accountList[i].getId())) {
                index = i;
                break;
            }
        }
        return index;
    }

    public boolean addAccount(Account account) {
        boolean result = false;
        if (getAccount(account.getId()) == null) {
            if (size == accountList.length) { // 数组已经满了
                // 扩大数组
                accountList = Arrays.<Account>copyOf(accountList, accountList.length + 10);
            }
            accountList[size++] = account;
            result = true;
        }
        return result;
    }

    public boolean removeAccount(String id) {
        boolean result = false;
        int index = indexOf(id);
        if (index >= 0 && Double.compare(accountList[index].getBalance(), 0.0) == 0) {
            for (int i = index; i < size - 1; i++) {
                accountList[i] = accountList[i + 1];
            }
            size--;
            result = true;
        }
        return result;
    }

    public double getTotalBalance() {
        double result = 0.0;
        for (int i = 0; i < size; i++) {
            result += accountList[i].getBalance();
        }
        return result;
    }

    public int getNumberOfCreditAccount() {
        int result = 0;
        for (int i = 0; i < size; i++) {
            if (accountList[i] instanceof CreditAccount) {
                result++;
            }
        }
        return result;
    }

    public Account[] getAllAccounts() {
        return Arrays.<Account>copyOf(accountList, size);
    }

    public int getSize() {
        return size;
    }
}
